import React, { Component } from 'react'
import { connect } from 'react-redux'
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import moment from "moment";
import selectorData from "share/selectorData";
import NumberRange from "../../financial-management/expense-view/component/number-range";
import { Badge } from "antd";
import menuRoute from "routes/menuRoute";
import Selector from "components/selector";

const DataHoc = WrappedComponent => {

  class Hoc extends Component {

    setWrappedInstance = ref => {
      this.wrappedInstance = ref;
    };

    searchForm = [
      {
        component: isTitle => <Selector
          allowClear={false}
          type={'setOfBooksByTenant'}
          params={{ roleType: 'TENANT' }}
          entity
          onChange={value => this.handleChangeSetOfBook(value, isTitle)}
        />,
        id: 'setOfBookId',
        judgeInTitle: true,
        label: messages('finance-4.key66')/*账套*/,
        initialValue: {
          setOfBooksName: this.props.company.setOfBooksName,
          id: this.props.company.setOfBooksId
        },
        tagUnclosed: true,
        parser: value => ({ setOfBookId : value ? value.id : undefined }),
        tagParser: value => value.setOfBooksName
      },
      {
        id: 'draweeCompanyId', label: messages('finance-4.key67')/*付款公司*/, component: 'Chooser',
        props: {
          type: 'available_company_setOfBooks',
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams: { enabled: true, setOfBooksId: this.props.company.setOfBooksId }
        },
        parser: value => ({
          draweeCompanyId: value && value.length ? value[0].id : undefined
        })
      },
      {
        id: 'companyIds', label: messages('finance-4.key68')/*批次公司*/, component: 'Chooser',
        props: {
          type: 'available_company_setOfBooks',
          labelKey: 'name',
          valueKey: 'id',
          single: true,
          listExtraParams:{ enabled: true, setOfBooksId: this.props.company.setOfBooksId }
        },
        parser: value => ({
          companyIds: value ? value.map(item => item.id) : null
        }),
        dataIndex: 'companyName'
      }, {
        id: 'batchNo', label: messages('finance-4.key69')/*订单批次号*/, component: 'Input',
        props: {
          placeholder: messages('finance-4.key70')/*请输入temp2*/
        },
        dataIndex: 'batchNo'
      }, {
        id: 'createDate', label: messages('finance-4.key71')/*创建日期*/, component: 'DateRangePicker',
        parser: value => ({
          createDateStart: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
          createDateEnd: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
        }),
        dataIndex: 'createDate'
      }, {
        id: 'createId', label: messages('finance-4.key72')/*创建人*/, component: 'Selector',
        props: {
          placeholder: messages('common.please.input')/*请输入*/ + messages('finance-4.key73')/*创建人姓名/工号*/,
          selectorItem: {
            ...selectorData['user'],
            key: 'id',
            url: `/api/users/v3/search?page=0&size=9999&roleType=TENANT&status=all`,
            label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
                (`（${record.status === 1002 ?
                    messages('finance-4.key74')/*待离职员工*/ :
                    messages('finance-4.key75')/*离职员工*/}）`
                ) :
                ''
            )}`)
          }
        },
        dataIndex: 'employeeName'
      }, {
        id: 'amount',
        label: messages('finance-4.key26')/*金额范围*/,
        component: <NumberRange/>,
        parser: value => ({
          totalAmountStart: value && value[0] ? value[0] : null,
          totalAmountEnd: value && value[1] ? value[1] : null
        }),
        tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`,
        dataIndex: 'totalAmount'
      }
    ];

    handleChangeSetOfBook = (value, isTitle) => {
      const { searchForm } = this.wrappedInstance.state;
      let setOfBooksId = searchForm.find(item => item.id === 'draweeCompanyId').props.listExtraParams.setOfBooksId;
      if (setOfBooksId !== value.id) {
        if (!isTitle) {
          this.wrappedInstance.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
            draweeCompanyId: undefined,
            companyIds: undefined
          });
        }
        searchForm.map(item => {
          if (item.id === 'draweeCompanyId' || item.id === 'companyIds') {
            item.props.listExtraParams = { setOfBooksId: value.id, enabled: true };
          }
        });
        this.wrappedInstance.setState({ searchForm });
      }
    };

    getSearchForm = key => {
      let res = deepFullCopy(this.searchForm);
      switch (key) {
        case 'wait-check':
        case 'wait-recheck':
          break;
        case 'done-check':
          res = res.concat([{
            id: 'checkDate', label: messages('finance-4.key76')/*复核日期*/, component: 'DateRangePicker',
            parser: value => ({
              checkDateStart: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              checkDateEnd: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            }),
            dataIndex: 'checkDate'
          }]);
          break;
        case 'done-recheck':
          res = res.concat([{
            id: 'preCheckDate', label: messages('finance-4.key76')/*复核日期*/, component: 'DateRangePicker',
            parser: value => ({
              preCheckDateStart: value && value[0] ? moment(value[0]).format('YYYY-MM-DD') : null,
              preCheckDateEnd: value && value[1] ? moment(value[1]).format('YYYY-MM-DD') : null
            }),
            dataIndex: 'preCheckDate'
          }]);
          break;
        default:
          break;
      }
      return res;
    };

    companyName = { title: messages('finance-4.key68')/*批次公司*/, dataIndex: 'companyName' };

    batchNo = {
      title: messages('finance-4.key69')/*订单批次号*/, dataIndex: 'batchNo',
      render: (value, record) => <a onClick={e => this.handleGoToBatch(e, record)}>{value}</a>
    };

    createdDate = { title: messages('finance-4.key71')/*创建日期*/, dataIndex: 'createdDate', render: value => moment(value).format('YYYY-MM-DD') };

    checkDate = { title: messages('finance-4.key76')/*复核日期*/, dataIndex: 'checkDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-' };

    preCheckDate = { title: messages('finance-4.key76')/*复核日期*/, dataIndex: 'preCheckDate', render: value => value ? moment(value).format('YYYY-MM-DD') : '-' };

    employeeCode = { title: messages('finance-4.key9')/*创建人工号*/, dataIndex: 'employeeCode' };

    employeeName = { title: messages('finance-4.key72')/*创建人*/, dataIndex: 'employeeName' };

    checkerCode = { title: messages('finance-4.key77')/*复核人工号*/, dataIndex: 'checkerCode' };

    preCheckerCode = { title: messages('finance-4.key77')/*复核人工号*/, dataIndex: 'preCheckerCode' };

    checkerName = { title: messages('finance-4.key78')/*复核人*/, dataIndex: 'checkerName' };

    preCheckerName = { title: messages('finance-4.key78')/*复核人*/, dataIndex: 'preCheckerName' };

    currency = { title: messages('common.currency')/*币种*/, dataIndex: 'currency', width: 56 };

    totalAmount = { title: messages('common.total.amount')/*总金额*/, dataIndex: 'totalAmount',
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currency)) };

    totalNum = { title: messages('finance-4.key79')/*订单明细数*/, dataIndex: 'totalNum' };

    payAccountName = {
      title: messages('finance-4.key80')/*付款账号户名-账号*/, dataIndex: 'payAccountName', width: 200,
      render: (value, record) => `${value}-${record.payAccountNumber}`
    };

    paymentDescription = {
      title: messages('finance-4.key81')/*付款方式*/, dataIndex: 'paymentDescription',
      render: (value, record) => record.paymentData ? record.paymentData.paymentDescription : '-'
    };

    remark = {
      title: messages('finance-4.key63')/*备注temp*/, dataIndex: 'remark',
      render: (value, record) => record.paymentData ? record.paymentData.remark : '-'
    };

    checkStatus = {
      title: messages('finance-4.key82')/*复核状态*/, dataIndex: 'checkStatus',
      render: value => {
        const statusMap = {
          '00': messages('finance-4.key83')/*复核不通过*/,
          '02': messages('finance-4.key84')/*待复核*/,
          '01': messages('finance-4.key85')/*复核通过*/
        };
        return <Badge status={value === '01' ? 'success' : 'error'} text={statusMap[value]}/>;
      }
    };

    preCheckStatus = {
      title: messages('finance-4.key82')/*复核状态*/, dataIndex: 'preCheckStatus',
      render: value => {
        const statusMap = {
          '00': messages('finance-4.key83')/*复核不通过*/,
          '02': messages('finance-4.key84')/*待复核*/,
          '01': messages('finance-4.key85')/*复核通过*/
        };
        return <Badge status={value === '01' ? 'success' : 'error'} text={statusMap[value]}/>;
      }
    };

    operate = {
      title: messages('common.operation')/*操作*/, dataIndex: 'checkStatus', fixed: 'right', width: 150,
      render: (value, record) => (
        <div>
          <a onClick={() => this.wrappedInstance.handleEdit(record)}>{messages('common.edit')/*编辑*/}</a>
          <span className='ant-divider'/>
          <a onClick={() => this.wrappedInstance.handlePass(record)}>{messages('common.pass')/*通过*/}</a>
          <span className='ant-divider'/>
          <a onClick={() => this.wrappedInstance.handleReject(record)}>{messages('common.reject')/*驳回*/}</a>
        </div>
      )
    };

    handleGoToBatch = (e, record) => {
      e.stopPropagation();
      this.context.router.push(menuRoute.getRouteItem('batch-detail','key').url
        .replace(':batchId', record.batchNo));
    };

    getColumns = key => {
      let columns;
      switch (key) {
        case 'wait-check':
          columns = [this.companyName, this.batchNo, this.createdDate, this.employeeCode, this.employeeName, this.currency,
            this.totalAmount, this.totalNum, this.payAccountName, this.paymentDescription, this.remark, this.operate];
          break;
        case 'wait-recheck':
          columns = [this.companyName, {
            title: messages('finance-4.key69')/*订单批次号*/, dataIndex: 'batchNo'
          }, this.createdDate, this.employeeCode, this.employeeName, this.currency,
            this.totalAmount, this.totalNum, this.payAccountName, this.paymentDescription, this.remark];
          break;
        case 'done-check':
          columns = [this.companyName, this.batchNo, this.checkDate, this.checkerCode, this.checkerName, this.currency,
            this.totalAmount, this.totalNum, this.payAccountName, this.paymentDescription, this.remark, this.checkStatus];
          break;
        case 'done-recheck':
          columns = [this.companyName, {
            title: messages('finance-4.key69')/*订单批次号*/, dataIndex: 'batchNo'
          }, this.preCheckDate, this.preCheckerCode, this.preCheckerName, this.currency,
            this.totalAmount, this.totalNum, this.payAccountName, this.paymentDescription, this.remark, this.preCheckStatus];
          break;
      }
      return columns;
    };

    render() {
      let props = { ...this.props, ref: this.setWrappedInstance };
      return (
        <WrappedComponent
          getSearchForm={this.getSearchForm}
          getColumns={this.getColumns}
          {...props}
        />
      )
    }

  }

  function mapStateToProps(state) {
    return {
      company: state.login.company
    }
  }

  Hoc.contextTypes = {
    router: React.PropTypes.object
  };

  return connect(mapStateToProps)(Hoc);
};

export default DataHoc;
